package com.vtech.spring.controller;

import com.vtech.spring.commons.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * TODO
 *
 * @author houzhiwei
 * @date 2018/5/13 13:48
 */
@Api
@Controller("/")
public class HelloWorldController {
    @GetMapping("thymeleaf")
    public String thymeleaf() {
        return "hello Thymeleaf";
    }

    @GetMapping("index")
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("index");
        view.addObject("msg", "hello thymeleaf model and view");
        return view;
    }

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("msg", "from TemplateController.helloHtml");
        // 返回 resources/templates下 HTML 页面的名称
        return "hello";
    }

    @GetMapping("ex")
    @ResponseBody
    public void exception(Model model) throws Exception {
        throw new Exception("A Exception test");
    }

    /**
     * 必须为Ajax请求时才会返回JSON，否则转到 error.html
     * curl -H "X-Requested-With: XMLHttpRequest" localhost:8080/spring/be
     *
     * @param model
     */
    @GetMapping(value = "be", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @ApiOperation(value = "异常捕获测试", notes = "A BusinessException test",produces = "application/xml,application/json")
    public void except(Model model) {
        throw new BusinessException("A BusinessException test", HttpStatus.NOT_ACCEPTABLE);
    }
}
